package com.warmlight.voicepacket.network.base;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.warmlight.voicepacket.common.Constants;
import com.warmlight.voicepacket.data.eventbus.Login;
import com.warmlight.voicepacket.http.AES;
import com.warmlight.voicepacket.utils.Log;
import com.warmlight.voicepacket.utils.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;

/**
 * 服务器返回基类
 */
@SuppressWarnings("unchecked")
public class BaseSubscriber<T> implements Subscriber<ResponseBody> {

    /**
     * 请求回调
     */
    private NetworkCallback<T> mNetworkCallback;
    private NetworkCallbackLike<T> mNetworkCallbackLike;

    private TypeToken typeToken;

    private String decode;

    public BaseSubscriber(NetworkCallback<T> networkCallback, TypeToken typeToken) {
        mNetworkCallback = networkCallback;
        this.typeToken = typeToken;
    }

    public BaseSubscriber(NetworkCallbackLike<T> networkCallback, TypeToken typeToken) {
        mNetworkCallbackLike = networkCallback;
        this.typeToken = typeToken;
    }

    @Override
    public void onSubscribe(Subscription s) {
        s.request(Long.MAX_VALUE);
    }

    @Override
    public void onNext(ResponseBody responseBody) {
        try {
            String responseStr = responseBody.string();
            Log.e("接口信息"+responseStr);

            //没有抛出异常，并且不为空
            if (!TextUtils.isEmpty(responseStr)) {
                //获取的data数据进行一次揭秘操作，然后拼接json
                JSONObject jsonObject;
                try {
                     jsonObject=new JSONObject(responseStr);
                     if (jsonObject.has("data")){
                         String msg = jsonObject.getString("msg");
                         String code = jsonObject.getString("code");
                         String time = jsonObject.getString("time");
                         String data = jsonObject.getString("data");
                         decode = new AES(time).decrypt(data);
                         //拼接json
                         responseStr = "{\"code\":"+code+",\"time\":"+time+",\"msg\":\""+msg+"\",\"data\":"+decode+"}";

                         if (TextUtils.equals("301",code)){
                             new Handler(Looper.getMainLooper()).post(new Runnable() {
                                 @Override
                                 public void run() {
                                     SPUtils.logout();
                                     EventBus.getDefault().post(new Login(false));
                                 }
                             });

                         }
                     }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //回调基类里面code值判断是否成功
                BaseResponse<T> baseResponse = (BaseResponse<T>) json2Obj(responseStr, typeToken.getType());
                //此处用来点赞的接口基类，decode返回成功就代表点赞成功
                //表示成功
                if (null != mNetworkCallbackLike) {
                    mNetworkCallbackLike.onSuccess_Like(responseStr);
                }

                if (baseResponse != null) {
                    if (baseResponse.code == Constants.HTTP_RESULT_SUCCESS) {
                        //表示成功
                        if (null != mNetworkCallback) {
                            mNetworkCallback.onSuccess(baseResponse, responseStr);
                        }
                    } else {
                        onError(new NullPointerException());
                    }
                } else {
                    onError(new NullPointerException());
                }
            } else {
                onError(new NullPointerException());
            }
        } catch (IOException e) {
            e.printStackTrace();
            onError(e);
        }
    }

    @Override
    public void onError(Throwable t) {
        if (null != mNetworkCallback) {
            mNetworkCallback.onError(t);
        }
    }

    @Override
    public void onComplete() {
    }

    /**
     * json转换
     */
    private Object json2Obj(String json, Type type) {
        Object object = null;
        try {
            object = new Gson().fromJson(json, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }
}
